import mysql from "mysql";
import md5 from "js-md5";
import LinkStore from "../storage/linkstore";

/**
 * 数据库遍历
 * @param {连接ID} linkId
 * @param {SQL语句} sql
 * @param {SQL语句的动态值} values
 * @returns
 */
var queryInner = function (linkId, sql, values) {
  let params = LinkStore.get(linkId);
  // 返回一个 Promise
  return new Promise((resolve, reject) => {
    var connection = mysql.createConnection(params);
    connection.connect();
    connection.query(sql, values, (err, result) => {
      if (err) {
        reject(err);
      } else {
        resolve(result);
      }
    });
    connection.end();
  });
};

/**
 * 获取连接所有表
 * @param {连接ID} linkId
 * @returns
 */
var tables = async function (linkId, like) {
  if (like == null || like == undefined) {
    like = "";
  }
  var sql =
    " select table_name tableName, engine engine,table_collation tableCollation, table_comment tableComment,version version, create_time createTime" +
    " from information_schema.tables" +
    " where table_schema = (select database())" +
    " and (table_name like ? or table_comment like ?)";
  var result = await queryInner(linkId, sql, [
    "%" + like + "%",
    "%" + like + "%",
  ]);
  if (result == null) {
    return [];
  }

  //console.log(result);
  //console.log(result);
  return result.map((o) => {
    return {
      id: md5(o.tableName),
      linkId: linkId,
      tableName: o.tableName,
      engine: o.engine,
      tableCollation: o.tableCollation,
      tableComment: o.tableComment,
      version: o.version,
      createTime: o.createTime,
    };
  });
};

var table = async function (linkId, tableId) {
  var list = await tables(linkId);

  var item = list.find((o) => o.id === tableId);

  return item;
};

/**
 * 获取列信息（内部类）
 * @param {连接ID} linkId
 * @param {表名} tableName
 * @returns
 */
var columnsInner = async function (linkId, tableId, tableName) {
  var sql =
    " select table_name tableName,column_name columnName, data_type dataType, column_comment columnComment, column_key columnKey, is_nullable nullable" +
    " from information_schema.columns" +
    " where table_name = ? and table_schema = (select database()) order by ordinal_position";
  var result = await queryInner(linkId, sql, tableName);

  console.log(result);

  return result.map((o) => {
    return {
      id: md5(o.columnName),
      tableId: tableId,
      tableName: o.tableName,
      columnName: o.columnName,
      dataType: o.dataType,
      columnComment: o.columnComment,
      columnKey: o.columnKey,
      nullable: o.nullable,
    };
  });
};

/**
 * 获取表的列
 * @param {连接ID} linkId
 * @param {表ID} tableId
 * @returns
 */
var columns = async function (linkId, tableId) {
  var list = await tables(linkId);

  var item = list.find((o) => o.id === tableId);

  var columnList = await columnsInner(linkId, tableId, item.tableName);

  return columnList;
};

/**
 * 获取表的详情信息
 * @param {连接ID} linkId
 * @param {表ID} tableId
 * @returns
 */
var details = async function (linkId, tableId) {
  var list = await tables(linkId);

  var item = list.find((o) => o.id === tableId);

  var columnList = await columnsInner(linkId, item.tableName);

  item.columnList = columnList;

  return item;
};

export default { tables, table, columns, details };
